package store.controller;

import store.dao.UserDAO;
import store.po.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("login");
        String loginName=request.getParameter("loginName");
        String pwd=request.getParameter("pwd");
        try {
            User user=new UserDAO().findByLoginName(loginName);
            if(user==null){
                request.setAttribute("msg","用户名不存在");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
                return;
            }
            if(!user.getPwd().equals(pwd)){
                request.setAttribute("msg","密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
                return;
            }
            request.getSession(true).setAttribute("user",user);
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
